package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
)

type TestController struct {
	beego.Controller
}

// Model Struct
type User struct {
	Id     int
	Name   string `orm:"size(100)"`
	Status string `orm:"size(1)"`
}
type List struct {
	Code int
	Data []User
	Msg  string
}
type success struct {
	Code int
	Msg  string
	Data string
}
type fail struct {
	Code int
	Msg  string
}
func init() {
	orm.RegisterModel(new(User))
}
func (this *TestController) List() {
	status := this.GetString("status")
	o := orm.NewOrm()
	var users []User
	qs := o.QueryTable("user")
	qs.Filter("status", status).All(&users)
	//for i := 0; i < len(users); i++{
	//}
	for i , user := range users {
		if user.Status == "Y" {
			users[i].Status = "正常";
		}
	}
	res := List{0, users, "成功"}
	this.Data["json"] = res
	this.ServeJSON()
}

func (this *TestController) User() {
	id, err := this.GetInt("id")
	if err != nil {
		badRes := fail{1, "id不能为空"}
		this.Data["json"] = badRes
		this.ServeJSON()
		return
	}
	o := orm.NewOrm()
	var users User
	qs := o.QueryTable("user")
	qs.Filter("id", id).One(&users)
	this.Data["json"] = users
	this.ServeJSON()
}

func (this *TestController) Add() {
	o := orm.NewOrm()
	user := User{Name: "test",Status:"Y"}
	id, err := o.Insert(&user)
	if err != nil {
		res := fail{0,"添加失败"}
		this.Data["json"] = res
	}else{
		res := success{0,"添加成功", strconv.FormatInt(id, 10)}
		this.Data["json"] = res
	}
	this.ServeJSON()
}

func (this *TestController) Get() {
	//u := user{}
	//err := c.ParseForm(&u)
	//if  err != nil {
	//	c.Ctx.WriteString("error")
	//}
	//println(u.id)
	//c.Ctx.WriteString("11111")
	//	var id int;
	jsoninfo := this.GetString("a")
	println(jsoninfo)
	id, _ := this.GetInt("id")
	println(id)
	this.Ctx.WriteString(string(id))
}

func (this *TestController) Post() {

	o := orm.NewOrm()

	user := User{Name: "slene"}

	// insert
	id, err := o.Insert(&user)
	fmt.Printf("ID: %d, ERR: %v\n", id, err)

	//this.Ctx.WriteString("Hello World!")

	//u := user{}
	//err := c.ParseForm(&u)
	//if  err != nil {
	//	c.Ctx.WriteString("error")
	//}
	//println(u.id)
	//c.Ctx.WriteString("11111")
	//	var id int;
	//b  := this.GetString("a")
	//	id,_ := this.GetInt("id")
	//	println(id)
	//this.Ctx.WriteString(string(id))
	//var a res
	//this.Data["json"] = a
	//this.ServeJSON()
}
